﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.EntityClient;
using System.Data.Linq;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using QuaManSys;
using System.IO;
using System.Web.UI.HtmlControls;
using QMSDAL;

namespace QuaManSys.InnerInfo
{

    public partial class InnerInfoRegist : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            //判断用户是否是非法访问
            if (Session["CurUser"] != null)
            {
                //从session中取出当前用户信息并显示
                CurUser user = (CurUser)Session["CurUser"];
                //判断是否具有登记权限
                bool roleAccess = Permission.JudgePermission(user, "1A", "A");
            
                if (roleAccess)
                {
                    if (!IsPostBack)
                    {
                        //CurUser user = (CurUser)Session["CurUser"];
                        txtInfoWrt.Text = user.employeeId;
                        txtInfoDep.Text = user.department;
                        txtWrtDat.Text = DateTime.Now.ToShortDateString();
                        initddlProNo();
                        txtMacTyp.Text = GCBH.GetJXGCBH(ddlProNo.Text);
                        txtMacNo.Text = GCBH.GetTFGCBH(ddlProNo.Text);
                        initResponDept();//初始化责任部门
                        initRelatedDept();//初始化checkbox
                    }
                    //根据工程编号获取机型
                    txtMacTyp.Text = GCBH.GetJXGCBH(ddlProNo.Text);
                    //根据工程编号获取机号
                    txtMacNo.Text = GCBH.GetTFGCBH(ddlProNo.Text);

                    txtDeptFoc.Attributes.Add("ReadOnly", "True");
                    string s = maxID();
                    lblNo.Text = AutoCreatID("HHM", s);
                }
                else
                {
                    Response.Write("<script>alert('您不具有当前访问权限！')</script>");
                    Response.Redirect("InnerMainPage.aspx");
                }

            }
            else
            {
                //跳转到登录页面
                Response.Redirect("~/Login.aspx");
            }
        }

        

        /*
   * 初始化责任部门下拉框选项
   */


        /// <summary>
        /// 将工程编号和后台数据库绑定
        /// </summary>

        private void initddlProNo()
        {
            DataSet ds = GCBH.GetAllProjectNumbers();
            foreach (DataTable dt in ds.Tables)
            {
                ddlProNo.Items.Clear();
                int count = 0;
                for (int culCol = 0; culCol < dt.Columns.Count; culCol++)
                {
                    for (int culRow = 0; culRow < dt.Rows.Count; culRow++)
                    {
                        ListItem li = new ListItem(dt.Rows[culRow][culCol].ToString());
                        ddlProNo.Items.Insert(count++, li);
                    }
                }
            }

        }

        //private void AutoFillProjectRel()
        //{
            
        //    using (var context = new QuaManSysEntities())
        //    {
        //        try
        //        {
        //            var result = from c in context.Tab_ProjectNo
        //                         where ddlProNo.Text == c.projectNo
        //                         select new { c.machinemodelNo, c.machineNo };
        //            txtMacTyp.Text = result.First().machinemodelNo;
        //            txtMacNo.Text = result.First().machineNo;
        //        }
        //        catch (EntitySqlException ex)
        //        {
        //            Console.WriteLine(ex.ToString());
        //        }
        //    }
        //}
        /// <summary>
        /// 自动显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlProNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtMacTyp.Text = GCBH.GetJXGCBH(ddlProNo.Text);
            txtMacNo.Text = GCBH.GetTFGCBH(ddlProNo.Text);
        }

        /// <summary>
        /// 提交到数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnInfoSub_Click(object sender, EventArgs e)
        {
            CurUser user = (CurUser)Session["CurUser"];
            if (Permission.JudgePermission(user, "1A", "A"))
            {
                #region 提交内部信息
                fileUpload();
                try
                {
                    string infoCat = "";
                    if (CheckBox1.Checked) { infoCat = "已处理（需后继关注）"; CheckBox2.Enabled = false; }
                    if (CheckBox2.Checked) { infoCat = "未处理（需跟踪处理）"; CheckBox1.Enabled = false; }

                    using (var db = new QuaManSysEntities())
                    {

                        InnerQualityInfo insertInner = new InnerQualityInfo
                        {
                            qualityInfoId = lblNo.Text,
                            projectNo = ddlProNo.Text,
                            components = txtComponent.Text,
                            producer = txtManufac.Text,
                            faultType = txtFaiTyp.Text,
                            projectCategory = infoCat,
                            name = txtPjNam.Text,
                            deadline = Convert.ToDateTime(txtProDL.Text),
                            customerLinker = txtCustomer.Text,
                            telephone = txtCusTel.Text,
                            specialDemands = txtSpeReq.Text,
                            informationSource = DDLInfoCla.Text,
                            levelOfImportance = DDLImpLev.Text,
                            description = txtInfoDsc.Text,
                            registrantName = txtInfoWrt.Text,
                            registrantDepart = txtInfoDep.Text,
                            //registDate = Convert.ToDateTime(txtWrtDat.Text),
                            registDate = DateTime.Now.Date,
                            recommendedTreatPlan = txtReqAdv.Text,
                            processingStatus = "分发",
                            processingResults = txtReqRsl.Text,
                            processingAssess = txtProCmm.Text,
                            informationCategory = txtPjCls.Text
                        };
                        db.InnerQualityInfo.Add(insertInner);
                        db.SaveChanges();

                        InnerResponsibleDepart resDept = new InnerResponsibleDepart
                        {
                            department = DDLDepRes.Text,
                            qualityInfoId = lblNo.Text,
                            isResponDepart = 1
                        };
                        db.InnerResponsibleDepart.Add(resDept);
                        db.SaveChanges();

                        Common.InnerRelatedDeptOperation.AddInnerRelatedDept(lblNo.Text, user.department);

                        string ss = txtDeptFoc.Text.ToString();
                        string[] ssd = ss.Split('|');

                        for (int i = 0; i < ssd.Length; i++)
                        {

                            InnerResponsibleDepart dept = new InnerResponsibleDepart
                            {
                                department = ssd[i],
                                qualityInfoId = lblNo.Text,
                                isResponDepart = 0
                            };
                            db.InnerResponsibleDepart.Add(dept);
                            db.SaveChanges();

                        }


                    }

                    Response.Redirect("SubmitSuccess.aspx");

                }

                catch (Exception ex)
                {
                    Response.Write("<Script>alert('提交失误');</Script>");
                    throw ex;
                }
                #endregion
            }
            else
            {
                Response.Write("<script>alert('权限不足，操作失败！');</script>");
            }
        }


        //private string GetInnerQuaNumber()
        //{
        //    string preNumber = "HHM";
        //    string year = DateTime.Now.Year.ToString();
        //    string number = GetNextNumber();
        //    number = preNumber + year + number;
        //    return number;
        //}

       
        /// <summary>
        /// 找最大的自动生成单号
        /// </summary>
        public static string maxID()
        {
            var context = new QuaManSysEntities();

            if (context.InnerQualityInfo.Count() == 0)
            {
                return "";

            }
            else
            {
                var query = from b in context.InnerQualityInfo
                            orderby b.qualityInfoId
                            select b.qualityInfoId;
                return query.Max();

            }



        }

        /// <summary>
        /// 生成自动编号
        /// </summary>
        /// <param name="flag"></param>
        /// <param name="TableName"></param>
        /// <param name="FieldName"></param>
        /// <returns></returns>
        public static string AutoCreatID(string flag, string maxID)
        {
            string dbDateTime = DateTime.Now.Year.ToString();
            //string Str = "select max(" + FieldName + ") id from " + TableName;//查询表中的字段
            //object obj = Datasource.DbHelperSQL.GetSingle(Str);//把查询字符串Str放到GetSingle()中执行查询(Command)并返回查询结果（对象）
            //string maxID = "";
            //if (obj != null)//返回（查询字符串）对象
            //    maxID = Datasource.DbHelperSQL.GetSingle(Str).ToString();
            string Result = "";
            if (maxID == "")//没有最大编号
            {
                Result = flag + DateTime.Now.Year + "001";//HHM2012001
            }
            else
            {
                //截取字符
                string strFirstFour = maxID.Substring(3, 4);
                string strLastThree = maxID.Substring(7, 3);
                if (dbDateTime == strFirstFour)//截取的最大编号（20090225）是否和数据库服务器系统时间相等
                {
                    string strNewThree = (Convert.ToInt32(strLastThree) + 1).ToString("000");//0000+1
                    Result = flag + DateTime.Now.Year + strNewThree;//HHM2012001
                }
                else
                {
                    Result = flag + DateTime.Now.Year + "001";
                }
            }
            return Result;
        }


        /// <summary>
        /// 绑定责任部门
        /// </summary>
        private void initResponDept()
        {
            DataSet ds = Department.GetAllDept();
            foreach (DataTable dt in ds.Tables)
            {
                int count = 0;
                for (int curCol = 0; curCol < dt.Columns.Count; curCol++)
                {
                    for (int curRow = 0; curRow < dt.Rows.Count; curRow++)
                    {
                        ListItem li = new ListItem(dt.Rows[curRow][curCol].ToString());
                        DDLDepRes.Items.Insert(count++, li);
                    }
                }
            }
        }



        /// <summary>
        /// 重新加载checkbox
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ResponDept_SelectedIndexChanged(object sender, EventArgs e)
        {
            initRelatedDept();
        }
        /// <summary>
        /// 初始化checkbox
        /// </summary>
        private void initRelatedDept()
        {
            DataSet ds = Department.GetAllDept();
            foreach (DataTable dt in ds.Tables)
            {
                txtDeptFoc.Text = "";
                cblKeyWords.Items.Clear();
                int count = 0;
                for (int curCol = 0; curCol < dt.Columns.Count; curCol++)
                {
                    for (int curRow = 0; curRow < dt.Rows.Count; curRow++)
                    {
                        if (dt.Rows[curRow][curCol].ToString() == DDLDepRes.Text) continue;
                        ListItem li = new ListItem(dt.Rows[curRow][curCol].ToString());
                        cblKeyWords.Items.Insert(count++, li);
                    }
                }
            }
        }

        #region 文件上传
        protected void fileUpload()
        {
            #region
            int cnt = Convert.ToInt16(hidden.Value.ToString());
            HtmlInputFile f = this.FileUploadD1;
            UpLoadFile(f.PostedFile);

            for (int i = 2; i <= cnt; i++)
            {
                HttpPostedFile f1 = Request.Files["FileUploadD" + i];
                UpLoadFile(f1);
            }
            #endregion

        }

        /// <summary>
        /// 文件上传。
        /// </summary>
        /// <param name="InputFile"></param>
        /// <param name="Path"></param>
        public string UpLoadFile(HttpPostedFile InputFile)
        {

            //判断有控件内容进入
            string b = "";
            string xdd = "";
            try
            {
                xdd = InputFile.FileName.ToString();//获取上传文件的名字
            }
            catch (Exception e)
            {
                return xdd;
            }
            if (xdd != "")
            {
                string path = "~/FileUploadCS/" + lblNo.Text + "/";

                string PRICE_FJ_FJMC = "";
                string PRICE_FJ_FJHZ = "";
                string PRICE_FJ_PATH_SC = "";
                string PRICE_FJ_PATH_XZ = "";

                PRICE_FJ_PATH_XZ = path;
                //上传全路径包括文件名G:\\新建文件夹 (4)\\新建 文本文档.txt
                PRICE_FJ_PATH_SC = InputFile.FileName;
                //文件名包括后缀 新建 文本文档.txt"
                PRICE_FJ_FJMC = PRICE_FJ_PATH_SC.Substring(PRICE_FJ_PATH_SC.LastIndexOf("\\") + 1);
                ////
                //建立上传对象
                //
                HttpPostedFile postedFile = InputFile;
                //文件名包括后缀 新建 文本文档.txt"
                string fileName = System.IO.Path.GetFileName(postedFile.FileName);
                //文件后缀
                PRICE_FJ_FJHZ = System.IO.Path.GetExtension(fileName);


                string phyPath = HttpContext.Current.Request.MapPath(PRICE_FJ_PATH_XZ);//获取文件所在根目录
                //判断路径是否存在,若不存在则创建路径
                DirectoryInfo upDir = new DirectoryInfo(phyPath);
                if (!upDir.Exists)
                {
                    upDir.Create();
                }
                //
                //保存文件
                //
                try
                {
                    postedFile.SaveAs(phyPath + PRICE_FJ_FJMC);//文件保存
                    return b = phyPath;

                }
                catch
                {
                    throw new ApplicationException("上传失败!");
                }
                //返回上传文件的信息
            }

            return b;
        }

        #endregion


       

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                fileUpload();
                Response.Write("<Script>alert('恭喜上传成功！');</Script>");
            }
            catch {

                Response.Write("<Script>alert('上传失败！');</Script>");
            }
        }

    }
}
